﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Drawing2D;
using System.Drawing.Imaging;


namespace EbayMaster
{
    public partial class FrmItem : Form
    {
        public String ItemSKU = null;

        public FrmItem()
        {
            InitializeComponent();
        }

        private InventoryItemType GetItemInfoFromUI(bool isInsert)
        {
            InventoryItemType item = new InventoryItemType();

            TreeNode node = this.treeViewCategories.SelectedNode;
            if (node == null)
            {
                MessageBox.Show("请选择商品类别");
                return null;
            }

            if (isInsert)
            {
                if (node.Tag.GetType() != typeof(CategoryType))
                {
                    MessageBox.Show("请选择商品类别");
                    return null;
                }

                CategoryType category = (CategoryType)node.Tag;
                if (category == null)
                {
                    MessageBox.Show("请选择商品类别");
                    return null;
                }

                item.CategoryId = category.CategoryId;
                if (item.CategoryId <= 0)
                {
                    MessageBox.Show("请选择商品类别");
                    return null;
                }
            }
            else
            {
                // modify
                if (node.Tag.GetType() != typeof(ItemCompactInfo))
                {
                    MessageBox.Show("请选择商品");
                    return null;
                }
            }

            item.ItemName = this.textBoxItemName.Text;
            if (item.ItemName == "")
            {
                MessageBox.Show("请输入商品名");
                return null;
            }

            item.ItemSKU = this.textBoxItemSKU.Text;
            if (item.ItemSKU == "")
            {
                MessageBox.Show("请输入商品SKU");
                return null;
            }

            if (this.textBoxItemImagePath.Text.Trim() == "")
            {
                if (isInsert)
                {
                    MessageBox.Show("请选择商品图片");
                    return null;
                }
            }
            else
            {
                string imagePath = this.textBoxItemImagePath.Text.Trim();
                if (File.Exists(imagePath) == false)
                {
                    MessageBox.Show("商品图片路径错误.");
                    return null;
                }

                //FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                //byte[] buffer = new byte[fs.Length];
                //fs.Read(buffer, 0, buffer.Length);
                //fs.Close();
                //item.ItemImage = buffer;
                item.ItemImagePath = imagePath;
            }

            if (this.textBoxItemStockShreshold.Text == "")
            {
                MessageBox.Show("商品库存警戒值错误");
                return null;
            }

            item.ItemStockShresholdNum = Int32.Parse(this.textBoxItemStockShreshold.Text.Trim());

            string itemStockStr = this.textBoxItemStock.Text;
            if (itemStockStr.Trim() == "")
            {
                MessageBox.Show("商品库存值错误");
                return null;
            }
            item.ItemStockNum = StringUtil.GetSafeInt(itemStockStr);

            item.ItemSourcingInfo = this.textBoxItemSourcingInfo.Text;

            item.ItemSourcingURL = this.textBoxSourcingURL.Text;

            string itemCostStr = this.textBoxItemCost.Text.Trim();
            if (itemCostStr == "")
            {
                MessageBox.Show("商品成本值错误");
                return null;
            }
            item.ItemCost = StringUtil.GetSafeDouble(itemCostStr);

            string itemWeightStr = this.textBoxItemWeight.Text.Trim();
            if (itemWeightStr == "")
            {
                MessageBox.Show("商品重量值错误");
                return null;
            }
            item.ItemWeight = StringUtil.GetSafeDouble(itemWeightStr);

            item.ItemCustomName = this.textBoxCustomName.Text.Trim();

            string itemCustomWeightStr = this.textBoxItemCustomWeight.Text.Trim();
            if (itemCustomWeightStr == "")
                item.ItemCustomWeight = 0.0;
            else
                item.ItemCustomWeight = StringUtil.GetSafeDouble(itemCustomWeightStr);

            string itemCustomCostStr = this.textBoxItemCustomValue.Text.Trim();
            if (itemCustomCostStr == "")
                item.ItemCustomCost = 0.0;
            else
                item.ItemCustomCost = StringUtil.GetSafeDouble(itemCustomCostStr);

            item.ItemAddDateTime = DateTime.Now;

            // IsGroupItem
            item.IsGroupItem = false;
            item.SubItemSKUs = "";

            return item;
        }

        private void buttonAddNewItem_Click(object sender, EventArgs e)
        {
            InventoryItemType item = GetItemInfoFromUI(true/*insert*/);
            if (item == null)
                return;
           
            int newItemId = ItemDAL.InsertOneItem(item);

            if (newItemId <= 0)
            {
                MessageBox.Show("不能添加新商品，可能商品的SKU和已有商品重复了!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Add this item to tree view.
            TreeNode[] nodes = this.treeViewCategories.Nodes.Find(item.CategoryId.ToString(), true);
            if (nodes.Length == 1)
            {
                TreeNode newNode = new TreeNode();
                newNode.Text = string.Format("[{0}] {1}", item.ItemSKU, item.ItemName); 
                ItemCompactInfo itemInfo = new ItemCompactInfo(newItemId, item.CategoryId, item.ItemName, item.ItemSKU);
                newNode.Tag = itemInfo;
                nodes[0].Nodes.Add(newNode);
            }

            MessageBox.Show("恭喜，添加新商品成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ShowItemWithSKU(String itemSKU)
        {
            DataTable dtItem = ItemDAL.GetItemTableBySKU(itemSKU);
            TreeNode[] nodes = this.treeViewCategories.Nodes.Find(itemSKU, true);
            if (nodes.Length == 0)
                return;

            this.treeViewCategories.SelectedNode = nodes[0];
        }

        private void FrmItem_Load(object sender, EventArgs e)
        {
            LoadAllCategories();
            LoadAllItems();

            if (ItemSKU != null && ItemSKU != "")
            {
                ShowItemWithSKU(ItemSKU);
                this.treeViewCategories.Enabled = false;
            }
        }

        public class ItemCompactInfo
        {
            public int ItemId;
            public int CategoryId;
            public string ItemName;
            public string ItemSKU;

            public ItemCompactInfo(int itemId, int catId, string itemName, string itemSKU)
            {
                this.ItemId = itemId;
                this.CategoryId = catId;
                this.ItemName = itemName;
                this.ItemSKU = itemSKU;
            }
        }   // class ItemCompactInfo

        private void LoadAllItems()
        {
            DataTable dtItems = ItemDAL.GetAllItems();
            if (dtItems.Rows.Count == 0)
                return;

            foreach (DataRow dr in dtItems.Rows)
            {
                int itemId = StringUtil.GetSafeInt(dr["ItemId"]);
                int itemCatId = StringUtil.GetSafeInt(dr["CategoryId"]);
                string itemName = StringUtil.GetSafeString(dr["ItemName"]);
                string itemSKU = StringUtil.GetSafeString(dr["ItemSKU"]);

                ItemCompactInfo itemInfo = new ItemCompactInfo(itemId, itemCatId, itemName, itemSKU);
                TreeNode itemNode = new TreeNode();
                itemNode.Text = string.Format("[{0}] {1}", itemSKU, itemName);
                itemNode.Tag = itemInfo;
                itemNode.Name = itemSKU;

                TreeNode[] nodes = this.treeViewCategories.Nodes.Find(itemCatId.ToString(), true);
                if (nodes.Length == 1)
                {
                    nodes[0].Nodes.Add(itemNode);
                }
            }
        }

        private void LoadAllCategories()
        {
            DataTable dtCategories = CategoryDAL.GetAllCategories();
            if (dtCategories.Rows.Count == 0)
                return;

            this.treeViewCategories.Nodes.Clear();

            for (int itNum = 0; itNum < 2; ++itNum)
            {
                foreach (DataRow dr in dtCategories.Rows)
                {
                    int catId = StringUtil.GetSafeInt(dr["CategoryId"]);
                    int parentCatId = StringUtil.GetSafeInt(dr["ParentCategoryId"]);
                    string catName = StringUtil.GetSafeString(dr["CategoryName"]);

                    CategoryType catType = new CategoryType();
                    catType.CategoryId = catId;
                    catType.ParentCategoryId = parentCatId;
                    catType.CategoryName = catName;

                    TreeNode newNode = new TreeNode();
                    newNode.Tag = catType;
                    newNode.Text = catName;
                    newNode.Name = catId.ToString();

                    if (parentCatId == -1 && itNum == 0)
                    {
                        this.treeViewCategories.Nodes.Add(newNode);
                    }
                    else if (parentCatId != -1 && itNum == 1)
                    {
                        TreeNode[] parentNodes = this.treeViewCategories.Nodes.Find(parentCatId.ToString(), true);
                        if (parentNodes.Length == 1)
                            parentNodes[0].Nodes.Add(newNode);
                    }
                }
            }

            this.treeViewCategories.ExpandAll();
            return;
        }

        public Image ResizeImg(Image img, int width, int height)
        {
            //create a new Bitmap the size of the new image
            Bitmap bmp = new Bitmap(width, height);
            //create a new graphic from the Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //draw the newly resized image
            graphic.DrawImage(img, 0, 0, width, height);
            //dispose and free up the resources
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }

        /// <summary>
        /// method for resizing an image
        /// </summary>
        /// <param name="img">the image to resize</param>
        /// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param>
        /// <returns></returns>
        public Image ResizeImg(Image img, int percentage)
        {
            //get the height and width of the image
            int originalW = img.Width;
            int originalH = img.Height;

            //get the new size based on the percentage change
            int resizedW = (int)(originalW * percentage);
            int resizedH = (int)(originalH * percentage);

            //create a new Bitmap the size of the new image
            Bitmap bmp = new Bitmap(resizedW, resizedH);
            //create a new graphic from the Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //draw the newly resized image
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            //dispose and free up the resources
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }

        private void buttonNavigateItemImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "图片文件(*.jpg,*.gif,*.bmp)|*.jpg;*.gif;*.bmp ";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filePath = dlg.FileName;
                this.textBoxItemImagePath.Text = filePath;
                Image image = Image.FromFile(filePath);
                Image resizedImage = ResizeImg(image, this.pictureBoxItemPic.Width, this.pictureBoxItemPic.Height);

                this.pictureBoxItemPic.Image = resizedImage;
                
            }
        }

        private void treeViewCategories_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.buttonDelItem.Enabled = false;
            this.buttonModifyItem.Enabled = false;

            TreeNode node = this.treeViewCategories.SelectedNode;
            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            int itemId = itemInfo.ItemId;
            DataTable dtItem = ItemDAL.GetItemTableById(itemId);

            if (dtItem.Rows.Count == 0)
                return;

            DataRow dr = dtItem.Rows[0];

            this.textBoxItemName.Text = StringUtil.GetSafeString(dr["ItemName"]);
            this.textBoxItemSKU.Text = StringUtil.GetSafeString(dr["ItemSKU"]);
            this.textBoxItemStockShreshold.Text = StringUtil.GetSafeString(dr["ItemStockShresholdNum"]);
            this.textBoxItemStock.Text = StringUtil.GetSafeString(dr["ItemStockNum"]);
            this.textBoxItemSourcingInfo.Text = StringUtil.GetSafeString(dr["ItemSourcingInfo"]);
            this.textBoxSourcingURL.Text = StringUtil.GetSafeString(dr["ItemSourcingURL"]);
            this.textBoxItemCost.Text = StringUtil.GetSafeString(dr["ItemCost"]);
            this.textBoxItemWeight.Text = StringUtil.GetSafeString(dr["ItemWeight"]);
            this.textBoxCustomName.Text = StringUtil.GetSafeString(dr["ItemCustomName"]);
            this.textBoxItemCustomWeight.Text = StringUtil.GetSafeString(dr["ItemCustomWeight"]);
            this.textBoxItemCustomValue.Text = StringUtil.GetSafeString(dr["ItemCustomCost"]);

            String imagePath = StringUtil.GetSafeString(dr["ItemImagePath"]);
            this.pictureBoxItemPic.Image = null;
            this.textBoxItemImagePath.Text = "";
            if (File.Exists(imagePath))
            {
                Image rawImage = Image.FromFile(imagePath);
                if (rawImage != null)
                {
                    int width = this.pictureBoxItemPic.Width;
                    int height = this.pictureBoxItemPic.Height;
                    Image image = ResizeImg(rawImage, width, height);
                    this.pictureBoxItemPic.Image = image;
                }
                this.textBoxItemImagePath.Text = imagePath;
            }
            

           this.buttonDelItem.Enabled = true;
           this.buttonModifyItem.Enabled = true;

        }

        private void checkBoxIsGroupItem_CheckStateChanged(object sender, EventArgs e)
        {

        }

        private void treeViewCategories_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
                return;

            TreeNode node = treeViewCategories.GetNodeAt(e.Location);
            if (node == null)
                return;

            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            contextMenuStripItem.Show(treeViewCategories, e.X, e.Y); ;
        }

        private void ToolStripMenuItemDelItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeViewCategories.SelectedNode;
            if (node == null)
                return;

            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            if (MessageBox.Show(string.Format("确认删除商品 {0}", itemInfo.ItemName), "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                == System.Windows.Forms.DialogResult.Yes)
            {
                bool result = ItemDAL.DeleteOneItem(itemInfo.ItemId);
                if (result)
                {
                    MessageBox.Show("删除商品成功", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    treeViewCategories.Nodes.Remove(node);
                }
                else
                {
                    MessageBox.Show("删除商品失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void buttonDelItem_Click(object sender, EventArgs e)
        {
            if (buttonDelItem.Enabled == false)
                return;

            // Should be refactored.
            TreeNode node = treeViewCategories.SelectedNode;
            if (node == null)
                return;

            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            if (MessageBox.Show(string.Format("确认删除商品 {0}", itemInfo.ItemName), "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 
                    == System.Windows.Forms.DialogResult.Yes)
            {
                bool result = ItemDAL.DeleteOneItem(itemInfo.ItemId);
                if (result)
                {
                    MessageBox.Show("删除商品成功", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    treeViewCategories.Nodes.Remove(node);
                }
                else
                {
                    MessageBox.Show("删除商品失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void buttonModifyItem_Click(object sender, EventArgs e)
        {
            if (this.buttonModifyItem.Enabled == false)
                return;

            // Should be refactored.
            TreeNode node = treeViewCategories.SelectedNode;
            if (node == null)
                return;

            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            InventoryItemType item = ItemDAL.GetItemById(itemInfo.ItemId);
            if (item == null)
                return;

            InventoryItemType newItemInfo = GetItemInfoFromUI(false);
            if (newItemInfo == null)
                return;
            newItemInfo.ItemId = item.ItemId;
            newItemInfo.CategoryId = item.CategoryId;
            if (newItemInfo.ItemImagePath == null)
                newItemInfo.ItemImagePath = item.ItemImagePath;
            newItemInfo.ItemNote = item.ItemNote;

            if (MessageBox.Show(string.Format("确认修改商品 {0}", itemInfo.ItemName), "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes)
            {
                bool result = ItemDAL.ModifyOneItem(newItemInfo);
                if (result)
                {
                    MessageBox.Show("修改商品成功", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    itemInfo.ItemName = newItemInfo.ItemName;
                    itemInfo.ItemSKU = newItemInfo.ItemSKU;
                    node.Tag = itemInfo;
                    if (newItemInfo.ItemName != item.ItemName)
                    {
                        node.Text = string.Format("[{0}] {1}", newItemInfo.ItemSKU, newItemInfo.ItemName);
                    }

                }
                else
                {
                    MessageBox.Show("修改商品失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void buttonNavigateItemSourcingURL_Click(object sender, EventArgs e)
        {
            string sourcingURL = this.textBoxSourcingURL.Text;
            if (sourcingURL == null || sourcingURL.Trim().Length == 0)
            {
                MessageBox.Show("网址为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!sourcingURL.StartsWith("http://"))
                sourcingURL = string.Format("http://{0}", sourcingURL);
            System.Diagnostics.Process.Start(sourcingURL);
        }

        private void buttonEditItemNote_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewCategories.SelectedNode;
            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
                return;

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            int itemId = itemInfo.ItemId;
            DataTable dtItem = ItemDAL.GetItemTableById(itemId);

            if (dtItem.Rows.Count == 0)
                return;

            FrmItemNote frmItemNote = new FrmItemNote();
            frmItemNote.ItemId = itemId;
            frmItemNote.ShowDialog();
        }

    }
}
